import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Link } from 'react-router';
import { Button, Row, Form, Input, message, Tabs, Icon, Popconfirm ,Spin} from 'antd';
import NavBar from '../common/NavBar';
import ContentBody from '../common/ContentBody';
import api from '../api';
import FormInput from './FormInput';

const TabPane = Tabs.TabPane;
const FormItem = Form.Item;

let uuid = 0;
class WeiXinReplay extends React.Component {
    constructor(props,context) {
        super(props,context);
        this.state = {
            curData:{
                reply_type: 'text',
                content: ''
            },
            curKeysData:{},
            loading:false,
        };
    }



    remove = async(k) => {
        const { form } = this.props;
        // can use data-binding to get
        const keys = form.getFieldValue('keys');
        // We need at least one passenger
        if (keys.length === 1) {
          return;
        }

        // can use data-binding to set
        form.setFieldsValue({
          keys: keys.filter(key => key !== k),
        });

        // 删除关键词
        let {curKeysData} = this.state;
        let jsonData = {...curKeysData};
        if(jsonData[k]){
            var result = await api('/reply/weixin/delKeysMsg',{reply_name:jsonData[k].reply_name});
            if(result.data){
                delete jsonData[k];
                this.setState({
                    curKeysData: jsonData
                });
            }
        }

    }

    add = () => {
        uuid++;
        const { form } = this.props;
        // can use data-binding to get
        const keys = form.getFieldValue('keys');
        const nextKeys = keys.concat(uuid);

        form.setFieldsValue({
          keys: nextKeys,
        });
    }

    //保存被关注回复
    handleInitSubmit = async(e) => {
        e.preventDefault();
        this.setState({
          loading:true,
        })
        let {curData} = this.state;

        if(curData.reply_type){


          let type = "";
          let materialUrl = "";

          if (curData.reply_type == "image") {
            type = "image";
            materialUrl = curData.imageUrl;
          }else if (curData.reply_type == "voice") {
            type = "voice";
            materialUrl = curData.voiceUrl;
          }else if (curData.reply_type == "video") {
            type = "video";
            materialUrl = curData.videoUrl;
          }else{

          }

          if (type && materialUrl) {//只是图片消息，视频，音频消息需要上传素材
            var r = await api('/weixin/upload/material',{filepath:materialUrl,type:type});
            
            if (r.errcode) {
              message.success("上传失败");
              return;
            }else{
              if (r.media_id) {
                let params = {content:'',type:''};
                let data = {};
                if("image" == curData.reply_type){
                  params.type = "IMAGE";
                  data = {imageUrl:curData.imageUrl,mediaId:r.media_id};
                }else if("voice" == curData.reply_type){
                  params.type = "VOICE";
                  data = {voiceUrl:curData.voiceUrl,voiceList:curData.voiceList,mediaId:r.media_id};
                }else if("video" == curData.reply_type){
                  params.type = "VIDEO";
                  data = {videoUrl:curData.videoUrl,videoTitle:curData.videoTitle,videoDescription:curData.videoDescription,videoList:curData.videoList,mediaId:r.media_id};
                }else{

                }

                params.content = JSON.stringify(data);
                var result = await api('/reply/weixin/addMsg',{params});
                if (result.cd == 0) {
                  
                  message.success("保存成功");
                  
                  this.setState({
                    loading:false,
                  })
                  return;
                }else{
                  this.setState({
                    loading:false,
                  })

                  message.success(result.msg);
                  return
                }
              }else{
                this.setState({
                    loading:false,
                  })
                message.error('上传失败，请重试')
                return;
              }
              
            }
          }else{//文字、图文消息不需要上传素材
            let params = {content:'',type:''};
            let data = {};
            if ("text" == curData.reply_type) {
              params.type = "TEXT";
              data = {textContent:curData.textContent};
            }else if("news" == curData.reply_type){
              params.type = "T_I";
              data = {newsTitle:curData.newsTitle,newsDescription:curData.newsDescription,newsGotoUrl:curData.newsGotoUrl,newsUrl:curData.newsUrl,jpgListTW:curData.jpgListTW};
            }else{

            }

            params.content = JSON.stringify(data);
            var result = await api('/reply/weixin/addMsg',{params});
            if (result.cd == 0) {
              
              message.success("保存成功");
              
              this.setState({
                loading:false,
              })
            }else{
              message.success(result.msg);

              this.setState({
                loading:false,
              })
            }
          }
        }
    }

    //保存关键词回复
    // handleKeysSubmit = async(e) => {
    //     e.preventDefault();
    //     let {curKeysData} = this.state;

    //     console.log("########", curKeysData);

    //     for (var key in curKeysData) {
    //         if(curKeysData[key].reply_type){
    //             var result = await api('/reply/weixin/postKeysMsg',{...curKeysData[key]});
    //         }
    //     }

    //     message.success("设置成功");

    // }

    onChange(activeKey){
        let {curKeysData} = this.state;
        let newKeysObj = {...curKeysData};

        if(typeof activeKey == 'object'){
            if(activeKey.target.id && activeKey.target.id.indexOf('names-')!=-1){
                let key = activeKey.target.id.split('-')[1];
                if(newKeysObj[key]){
                    newKeysObj[key]['reply_name'] = activeKey.target.value;
                }else{
                    newKeysObj[key] = {};
                    newKeysObj[key]['reply_name'] = activeKey.target.value;
                }

                this.setState({
                    curKeysData: newKeysObj
                });
            }
        }
    }

   async componentWillMount(){
      this.getData();

    }

    async componentDidMount(){
        // this.add();
        // var result = await api('/reply/weixin/getInitMsg');

        // var result_key = await api('/reply/weixin/getKeysMsg');
        // console.log('/reply/weixin/getInitMsg==========result',result)
        // console.log('/reply/weixin/getInitMsg==========result_key',result_key);

        // let curKeysData = {};
        // if(result_key.data && result_key.data.length>0){
        //     for (var i = 0; i < result_key.data.length; i++) {
        //         curKeysData[i+1] = result_key.data[i];
        //         this.add();
        //     }
        // }else{
        //     this.add();
        // }

        // if(result.data){
        //     this.setState({
        //         curData: result.data,
        //         curKeysData: curKeysData
        //     });
        // }else{
        //     this.setState({
        //         curData: {
        //             reply_type: 'text',
        //             content: ''
        //         },
        //         curKeysData: curKeysData
        //     });
        // }

    }

    async getData(){
      let result = await api('/reply/weixin/getMsg');
      if (result.cd != 0) {
        message.error(result.msg);
        return;
      }
      console.log('/reply/weixin/getMsg=======',result);

      this.add();
      let {curData} = this.state;
      if (result.data && result.data.content) {
        let data = JSON.parse(result.data.content);
        if ("TEXT" == result.data.type) {
            curData.reply_type = "text";
            curData.textContent = data.textContent;
          }else if("IMAGE" == result.data.type){
            curData.reply_type = "image";
            curData.imageUrl = data.imageUrl;
            curData.jpgList = [{
                uid: -1,
                status: 'done',
                url: data.imageUrl,
            }]
          }else if("T_I" == result.data.type){
            curData.reply_type = "news";
            curData.newsTitle = data.newsTitle;
            curData.newsDescription = data.newsDescription;
            curData.newsGotoUrl = data.newsGotoUrl;
            curData.newsUrl = data.newsUrl;
            curData.jpgListTW = data.jpgListTW;
          }else if("VOICE" == result.data.type){
            curData.reply_type = "voice";
            curData.voiceUrl = data.voiceUrl;
            curData.voiceList = data.voiceList;
          }else if("VIDEO" == result.data.type){
            curData.reply_type = "video";
            curData.videoUrl = data.videoUrl;
            curData.videoTitle = data.videoTitle;
            curData.videoDescription = data.videoDescription;
            curData.videoList = data.videoList;
          }else{

          }
          this.setState({
            curData,
          })
      }
      
    }

    async deleteMsg(){
      let result = await api('/reply/weixin/delete');
      if (result.cd != 0) {
        message.error(result.msg);
        return;
      }
      message.success("删除成功！");
    }

    render() {
         const { getFieldDecorator, getFieldValue } = this.props.form;
         const formItemLayout = {
           labelCol: {
             xs: { span: 24 },
             sm: { span: 1 },
           },
           wrapperCol: {
             xs: { span: 24 },
             sm: { span: 20 },
           },
         };
         const formItemLayoutWithOutLabel = {
           wrapperCol: {
             xs: { span: 24, offset: 0 },
             sm: { span: 20, offset: 0 },
           },
         };

         let {curKeysData,curData} = this.state;

         getFieldDecorator('keys', { initialValue: [] });

         // const keys = getFieldValue('keys');
         // const formItems = keys.map((k, index) => {
         //   return (
         //     <FormItem
         //       required={false}
         //       key={k}
         //     >
         //       <div className="ant-form-item" style={{paddingLeft:0, marginBottom:'8px', marginTop:index === 0 ? 0 : 20, borderTop: index === 0 ? 0 : '1px dashed #e3e3e3'}}>关键词：（完全匹配）</div>
         //       {getFieldDecorator(`names-${k}`, {
         //         validateTrigger: ['onChange', 'onBlur'],
         //         rules: [{
         //           required: true,
         //           whitespace: true,
         //           message: "请添加关键词",
         //         }],
         //         initialValue: (curKeysData[k] && curKeysData[k].reply_name)||''
         //       })(
         //          <Input placeholder="请输入关键词" style={{ marginRight: 8 }} id={`names-${k}`} onChange={this.onChange.bind(this)}/>
         //       )}

         //       <FormInput parent={this} keys={k} curData={curKeysData[k]}/>
         //       {keys.length > 1 ? (
         //           <Popconfirm title="确认删除么?" onConfirm={() => this.remove(k)} okText="确定" cancelText="取消">
         //               <Button
         //                   style={{marginTop: 10}}
         //                   icon="minus-circle-o"
         //                   type="danger"
         //                   disabled={keys.length === 1}
         //               >删除</Button>
         //            </Popconfirm>

         //       ) : null}
         //     </FormItem>
         //   );
         // });

        return (
             <div>
              <Spin spinning={this.state.loading}>
                <NavBar navs={[{title:'微信自动回复管理'}]} />
                <ContentBody className='container' contentClass="card-container-bg">
                    <div className="card-container">
                    <div className='text-right'>
                      <Button
                      type='primary'
                      onClick={this.deleteMsg.bind(this)}
                      
                    >
                      删除
                    </Button>
                    </div>
                    
                        <Tabs type="card" onChange={this.onChange.bind(this)}>
                          <TabPane tab="扫码开门自动回复消息" key="1">
                              <Form onSubmit={this.handleInitSubmit}>
                                  <FormItem {...formItemLayoutWithOutLabel}>
                                      {this.state.curData.reply_type?<FormInput parent={this} ref="initForm" curData={curData}/>:null}
                                  </FormItem>
                                  <FormItem {...formItemLayoutWithOutLabel}>
                                      <Button type="primary" htmlType="submit">保存</Button>
                                  </FormItem>
                              </Form>
                          </TabPane>
                          {/*<TabPane tab="设置关键词自动回复" key="2">
                              <Form onSubmit={this.handleKeysSubmit}>
                                  {formItems}
                                  <FormItem {...formItemLayoutWithOutLabel}>
                                    <Button type="dashed" onClick={this.add} style={{ width: '100%' }}>
                                      <Icon type="plus" /> 添加关键词
                                    </Button>
                                  </FormItem>

                                  <FormItem {...formItemLayoutWithOutLabel}>
                                      <Button type="primary" htmlType="submit">保存</Button>
                                  </FormItem>
                              </Form>
                          </TabPane>*/}
                        </Tabs>
                     </div>
                </ContentBody>
                </Spin>
            </div>
        );
    }
}

const WrappedDynamicFieldSet = Form.create()(WeiXinReplay);
export default WrappedDynamicFieldSet;

WeiXinReplay.contextTypes= { router: React.PropTypes.object.isRequired};
